<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2022/8/22
 * Time: 11:16
 */

namespace app\common\lib;


use Endroid\QrCode\Color\Color;
use Endroid\QrCode\Logo\Logo;
use Endroid\QrCode\QrCode;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeEnlarge;
use Endroid\QrCode\RoundBlockSizeMode\RoundBlockSizeModeMargin;
use Endroid\QrCode\Writer\PngWriter;

class QRCodeImage
{
    protected $key;

    protected static $instance;

    public static function getInstance()
    {
        //        if(is_object(self::$instance)){
//            return self::$instance;
//        }
        return self::$instance = new self();
    }

    public function generateUserQrCode($data)
    {
        $logo = runtime_path('logo.png');//logo的图片地址
        return $this->generateQrCode($data);
    }

    public function generateQrCode($data,$logo='',$qrWith=200,$qrMargin=0)
    {
        $filename = runtime_path('qrcode/temp_qrcode_'.uniqid().'.png');
        Common::mkdirs(dirname($filename));

        $qrcodeColor = new Color(255,255,255,0);
        $roundBlockSize = (new RoundBlockSizeModeMargin(100));
        $qrcode = QrCode::create($data)->setSize($qrWith)->setMargin($qrMargin)->setBackgroundColor($qrcodeColor)->setRoundBlockSizeMode($roundBlockSize);
        (new PngWriter())->write($qrcode)->saveToFile($filename);

        if (is_file($logo)) {
            $QR             = imagecreatefromstring(file_get_contents($filename));
            $logo           = imagecreatefromstring(file_get_contents($logo));
            $QR_width       = imagesx($QR);
            $QR_height      = imagesy($QR);
            $logo_width     = imagesx($logo);
            $logo_height    = imagesy($logo);
            $logo_qr_width  = $QR_width / 5;
            $scale          = $logo_width / $logo_qr_width;
            $logo_qr_height = $logo_height / $scale;
            $from_width     = ($QR_width - $logo_qr_width) / 2;
            //var_dump($QR_width,$logo_width,$logo_height,$logo_qr_width,$logo_qr_height);
            imagecopyresampled($QR, $logo, $from_width, $from_width, 0, 0, $logo_qr_width, $logo_qr_height, $logo_width, $logo_height);
            imagepng($QR, $filename); //跟logo合并之后的地址
            file_put_contents($filename,file_get_contents($filename));
        }

        $result = TencentCos::getInstance()->uploadLocalFile($filename,'qrcode');
        $link = 'https://'.$result['Location'];

        unlink($filename);

        return $link;
    }
}